# from search_music import app as application
import os
from app import create_app
from flask import make_response
import logging
import json
from flask_cors import *
from app.encrypt.Encrypt import AESCipher

# logging.basicConfig(level=logging.DEBUG, filename='log_new.txt', filemode='a',
#                     format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s')
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
CORS(app, supports_credentials=True)


@app.errorhandler(404)
def page_not_found(e):
    app.logger.exception('error 500: %s', e)
    response = make_response('Not Find page', 404)
    return response


@app.errorhandler(500)
def internal_server_error(e):
    app.logger.exception('error 500: %s', e)
    response = make_response('internal server error', 500)
    response.status_code = 500
    return response


@app.errorhandler(502)
def internal_server_error(e):
    app.logger.exception('error 502: %s', e)
    response = make_response('Bad Gateway', 502)
    response.status_code = 500
    return response

@app.after_request
def after(res):
    headers = res.headers
    status = res.status
    if app.config['ISTRANSMISSIONENCRYPT'] == True:
        data = res.get_json()
        if data is None:
            return res
        print(data)
        encryptor = AESCipher(app.config['SECRET_KEY'])
        msg = json.dumps(data['datas'])
        data['datas'] = encryptor.encryptByAes(msg)
        res.response = json.dumps(data)
        res = make_response(json.dumps(data),status,headers)
    return res


if __name__ == '__main__':
    app.debug = True
    app.run(host='127.0.0.1', port='5000')
